package com.ukefu.webim.service.httpserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

public class HttpFileServer extends Thread{
	private int port ; 
	private String url ;
	private String redirect ;
	public HttpFileServer(final int port ,  final String url , final String redirect) {
		this.port = port ;
		this.url = url ;
		this.redirect = redirect ;
	}
	public void run(){
		EventLoopGroup bossGroup=new NioEventLoopGroup();
		EventLoopGroup workerGroup=new NioEventLoopGroup();
		try{
			ServerBootstrap bootstrap=new ServerBootstrap();
			bootstrap.group(bossGroup,workerGroup)
				.channel(NioServerSocketChannel.class)
				.childHandler(new ChannelInitializer<SocketChannel>() {
					protected void initChannel(SocketChannel socketChannel) throws Exception {
						socketChannel.pipeline().addLast("http-decoder",new HttpRequestDecoder());
						socketChannel.pipeline().addLast("http-aggregator",new HttpObjectAggregator(65536));
						socketChannel.pipeline().addLast("http-encoder",new HttpResponseEncoder());
						socketChannel.pipeline().addLast("http-chunked",new ChunkedWriteHandler());
						socketChannel.pipeline().addLast("fileServerHandler",new HttpFileServerHandler(url , redirect));
	
					}
				});
			ChannelFuture future = bootstrap.bind("0.0.0.0",port).sync();
			future.channel().closeFuture().sync();
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}

	}
}
